namespace eval negotiate {
    set seq 0
}

proc negotiate::get_handler {connid from lang child} {
    variable handler

    debugmsg negotiate "get: [list $from $child]"

    jlib::wrapper:splitxml $child tag vars isempty chdata children

    if {$tag == "query"} {
	foreach item $children {
	    jlib::wrapper:splitxml $item tag1 vars1 isempty1 chdata1 children1
	    if {$tag1 == "feature"} {
		set type [jlib::wrapper:getattr $vars1 type]

		if {![info exists handler($type)]} {
		    
		    return [list error cancel feature-not-implemented]
		}

		set opts {}
		foreach item1 $children1 {
		    jlib::wrapper:splitxml $item1 tag2 vars2 isempty2 \
			chdata2 children2
		    if {$tag2 == "option"} {
			lappend opts $chdata2
		    }
		}
		# TODO
		set opts [$handler($type) $from $type $opts]

		set opttags {}
		foreach opt $opts {
		    lappend opttags [jlib::wrapper:createtag option \
					 -chdata $opt]
		}

		set res [jlib::wrapper:createtag query \
			     -vars {xmlns jabber:iq:negotiate} \
			     -subtags [list [jlib::wrapper:createtag feature \
						 -vars [list type $type] \
						 -subtags $opttags]]]
		return [list result $res]
	    }
	}
    }
}

iq::register_handler get query jabber:iq:negotiate negotiate::get_handler

proc negotiate::register_handler {type h} {
    variable handler

    set handler($type) $h
}

proc negotiate::send_request {connid to type {options {}}} {
    variable seq
    variable tmp

    set i [incr seq]

    set opttags {}
    foreach opt $options {
	lappend opttags [jlib::wrapper:createtag option -chdata $opt]
    }

    jlib::send_iq get \
	[jlib::wrapper:createtag query \
	     -vars {xmlns jabber:iq:negotiate} \
	     -subtags [list [jlib::wrapper:createtag feature \
				 -vars [list type $type] \
				 -subtags $opttags]]] \
	-to $to \
	-command [list negotiate::recv_request_response $i] \
	-connection $connid

    vwait [namespace current]::tmp($i)
    set res $tmp($i)
    unset tmp($i)
    return $res
}

proc negotiate::recv_request_response {seq res child} {
    variable tmp

    if {$res != "OK"} {
	set tmp($seq) [list ERR $child]
	return
    }

    jlib::wrapper:splitxml $child tag vars isempty chdata children

    if {$tag == "query"} {
	foreach item $children {
	    jlib::wrapper:splitxml $item tag1 vars1 isempty1 chdata1 children1
	    if {$tag1 == "feature"} {
		set type [jlib::wrapper:getattr $vars1 type]

		set opts {}
		foreach item1 $children1 {
		    jlib::wrapper:splitxml $item1 tag2 vars2 isempty2 \
			chdata2 children2
		    if {$tag2 == "option"} {
			lappend opts $chdata2
		    }
		}
		set tmp($seq) [list OK $opts]
	    }
	}
    }
}


